"""
增强API接口 - 支持新功能
"""

from flask import Flask, request, jsonify
from .enhanced_services import EnhancedBilibiliService, LearningAnalyticsService, EnhancedAIService
from .bilibili_service import run_async
import json


def register_enhanced_routes(app: Flask):
    """注册增强API路由"""

    enhanced_bilibili_service = EnhancedBilibiliService()
    learning_service = LearningAnalyticsService()
    enhanced_ai_service = EnhancedAIService()

    @app.route('/api/series/analyze', methods=['POST'])
    def analyze_series_course():
        """分析UP主系列课程"""
        try:
            data = request.get_json()
            uid = data.get('uid', '')

            if not uid:
                return jsonify({
                    'success': False,
                    'error': '请提供UP主UID'
                }), 400

            result = run_async(enhanced_bilibili_service.analyze_series_course(int(uid)))
            return jsonify(result)

        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'分析系列课程失败: {str(e)}'
            }), 500

    @app.route('/api/recommendations', methods=['POST'])
    def get_recommendations():
        """获取相关推荐"""
        try:
            data = request.get_json()
            bvid = data.get('bvid', '')
            count = data.get('count', 10)

            if not bvid:
                return jsonify({
                    'success': False,
                    'error': '请提供视频BVID'
                }), 400

            result = run_async(enhanced_bilibili_service.get_related_recommendations(bvid, count))
            return jsonify(result)

        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'获取推荐失败: {str(e)}'
            }), 500

    @app.route('/api/learning/path', methods=['POST'])
    def create_learning_path():
        """创建学习路径"""
        try:
            data = request.get_json()
            topic = data.get('topic', '')
            level = data.get('level', 'beginner')

            if not topic:
                return jsonify({
                    'success': False,
                    'error': '请提供学习主题'
                }), 400

            result = run_async(enhanced_bilibili_service.create_learning_path(topic, level))
            return jsonify(result)

        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'创建学习路径失败: {str(e)}'
            }), 500

    @app.route('/api/learning/track', methods=['POST'])
    def track_learning():
        """跟踪学习进度"""
        try:
            data = request.get_json()
            user_id = data.get('user_id', 'anonymous')
            video_bvid = data.get('video_bvid', '')
            progress_data = data.get('progress', {})

            if not video_bvid:
                return jsonify({
                    'success': False,
                    'error': '请提供视频BVID'
                }), 400

            result = run_async(learning_service.track_learning_progress(user_id, video_bvid, progress_data))
            return jsonify(result)

        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'跟踪学习进度失败: {str(e)}'
            }), 500

    @app.route('/api/knowledge/map', methods=['POST'])
    def generate_knowledge_map():
        """生成知识图谱"""
        try:
            data = request.get_json()
            topic = data.get('topic', '')
            videos = data.get('videos', [])

            if not topic or not videos:
                return jsonify({
                    'success': False,
                    'error': '请提供主题和视频列表'
                }), 400

            result = run_async(learning_service.generate_knowledge_map(topic, videos))
            return jsonify(result)

        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'生成知识图谱失败: {str(e)}'
            }), 500

    @app.route('/api/personalized/advice', methods=['POST'])
    def get_personalized_advice():
        """获取个性化学习建议"""
        try:
            data = request.get_json()
            user_profile_data = data.get('user_profile', {})
            video_analysis = data.get('video_analysis', {})

            # 构建用户画像对象
            from .enhanced_services import UserProfile
            user_profile = UserProfile(
                uid=user_profile_data.get('uid', 'anonymous'),
                interests=user_profile_data.get('interests', []),
                level=user_profile_data.get('level', 'beginner'),
                history=user_profile_data.get('history', []),
                preferences=user_profile_data.get('preferences', {}),
                learning_goals=user_profile_data.get('learning_goals', []),
                study_time=user_profile_data.get('study_time', 0)
            )

            result = run_async(enhanced_ai_service.generate_personalized_learning_advice(user_profile, video_analysis))
            return jsonify(result)

        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'获取个性化建议失败: {str(e)}'
            }), 500

    @app.route('/api/batch/analyze', methods=['POST'])
    def batch_analyze():
        """批量分析视频"""
        try:
            data = request.get_json()
            bv_list = data.get('bv_list', [])
            analysis_type = data.get('analysis_type', 'summary')

            if not bv_list:
                return jsonify({
                    'success': False,
                    'error': '请提供视频BVID列表'
                }), 400

            if len(bv_list) > 10:  # 限制批量数量
                return jsonify({
                    'success': False,
                    'error': '批量分析最多支持10个视频'
                }), 400

            results = []
            for bvid in bv_list:
                try:
                    # 调用原有的分析接口
                    from app import bilibili_service, ai_service
                    video_info_result = run_async(bilibili_service.get_video_info(bvid))
                    if video_info_result['success']:
                        # 这里可以调用不同的分析类型
                        result = {
                            'bvid': bvid,
                            'success': True,
                            'video_info': video_info_result['data'],
                            'status': 'completed'
                        }
                    else:
                        result = {
                            'bvid': bvid,
                            'success': False,
                            'error': video_info_result['error'],
                            'status': 'failed'
                        }
                except Exception as e:
                    result = {
                        'bvid': bvid,
                        'success': False,
                        'error': str(e),
                        'status': 'error'
                    }

                results.append(result)

            return jsonify({
                'success': True,
                'data': {
                    'total': len(bv_list),
                    'completed': len([r for r in results if r['success']]),
                    'failed': len([r for r in results if not r['success']]),
                    'results': results
                }
            })

        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'批量分析失败: {str(e)}'
            }), 500

    @app.route('/api/export/notes', methods=['POST'])
    def export_study_notes():
        """导出学习笔记"""
        try:
            data = request.get_json()
            content = data.get('content', '')
            format_type = data.get('format', 'markdown')
            filename = data.get('filename', '学习笔记')

            if not content:
                return jsonify({
                    'success': False,
                    'error': '请提供笔记内容'
                }), 400

            # 根据格式生成不同类型的笔记
            if format_type == 'markdown':
                export_content = f"# {filename}\n\n{content}"
                content_type = 'text/markdown'
                file_extension = '.md'
            elif format_type == 'html':
                export_content = f"""
                <!DOCTYPE html>
                <html>
                <head>
                    <title>{filename}</title>
                    <meta charset="utf-8">
                    <style>
                        body {{ font-family: Arial, sans-serif; margin: 40px; }}
                        h1 {{ color: #333; }}
                        h2 {{ color: #666; }}
                        p {{ line-height: 1.6; }}
                        .keyword {{ background: #ffffcc; padding: 2px 4px; }}
                    </style>
                </head>
                <body>
                    <h1>{filename}</h1>
                    <div>{content.replace('\n', '<br>')}</div>
                </body>
                </html>
                """
                content_type = 'text/html'
                file_extension = '.html'
            else:
                export_content = content
                content_type = 'text/plain'
                file_extension = '.txt'

            return jsonify({
                'success': True,
                'data': {
                    'content': export_content,
                    'content_type': content_type,
                    'filename': filename + file_extension
                }
            })

        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'导出笔记失败: {str(e)}'
            }), 500

    @app.route('/api/search/advanced', methods=['POST'])
    def advanced_search():
        """高级搜索"""
        try:
            data = request.get_json()
            keyword = data.get('keyword', '')
            filters = data.get('filters', {})
            page = data.get('page', 1)

            if not keyword:
                return jsonify({
                    'success': False,
                    'error': '请提供搜索关键词'
                }), 400

            # 构建搜索参数
            search_params = {
                'keyword': keyword,
                'duration': filters.get('duration', 'all'),  # all, short, medium, long
                'time_range': filters.get('time_range', 'all'),  # all, week, month, year
                'order': filters.get('order', 'relevance'),  # relevance, play, upload
                'category': filters.get('category', 'all')
            }

            # 这里可以集成更复杂的搜索逻辑
            result = run_async(enhanced_bilibili_service.advanced_search(search_params, page))

            return jsonify(result)

        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'高级搜索失败: {str(e)}'
            }), 500